# 红楼梦人物统计
import jieba
import csv
import pstats
import profile
class NameCount():
     def getNameTimesSort(self, name_list, txt_path):
         # 添加jieba分词
        mydict = ['琏二奶奶', '凤哥儿', '凤丫头', '宝姑娘', '颦儿', '二姑娘', '三姑娘', '四姑娘', '云妹妹', '蓉大奶奶']
        for item in mydict:
            jieba.add_word(item)
        #打开并读取txt文件
        txt = open('redstone.txt','r',encoding='utf-8').read()
         # 定义别名列表
        bieming = [["王熙凤", "凤丫头", '琏二奶奶', '凤姐', '凤哥儿', '凤辣子','熙凤'],["林妹妹", "黛玉", '林姑娘', '林黛玉'], ["宝钗", '宝姑娘', '宝丫头', '宝姐姐', '薛宝钗'],
                   ['探春', '三姑娘', '贾探春'], ['湘云', '云妹妹', '史湘云'],['迎春', '二姑娘', '贾迎春'],['元春', '大姑娘', '娘娘', '贵妃', '元妃', '贾元春'],
                   ['惜春', '四姑娘', '贾惜春'], ['妙玉'],['巧姐'], ['李纨', '大嫂子'], ['秦可卿', '可卿', '蓉大奶奶']]
        words = jieba.lcut(txt)
        counts = {}
        for word in words:
            if len(word) == 1:
                continue
            else:
                counts[word] = counts.get(word, 0) + 1
        # 计算出场次数（各个别名的合计次数）
        lst = list()
        for i in range(12):
            lt = 0
            for item in bieming[i]:
                lt += counts.get(item, 0)
            lst.append(lt)
        items = list()
        for i in range(12):
            items.append([name_list[i], lst[i]])
        items.sort(key=lambda x: x[1], reverse=True)
        f = open('红楼梦人物统计.csv', 'w', newline='', encoding='utf-8')
        csv_writer = csv.writer(f)
        csv_writer.writerow(['红楼梦人物统计'])
        csv_writer.writerow(["姓名", "出现次数"])
        for i in range(12):
            word, count = items[i]
            csv_writer.writerow([word, count])
            print("{0:<10}{1:>5}".format(word, count))
        f.close()      
        return items
if __name__ == '__main__':

    # 参与统计的人名列表，可修改成自己想要的列表
    name_list = ['熙凤', '黛玉', '宝钗', '探春', '湘云', '迎春', '元春', '惜春', '妙玉', '巧姐', '李纨', '可卿']
    # txt文件所在路径
    txt_path = 'redstone.txt'
    NameCount().getNameTimesSort(name_list,txt_path)
